import MyRequest
import Interface
import data

import hashlib
import tkinter as tk
import tkinter.messagebox
import json

loginUrl = data.baseUrl + '/users/login'


def check():
    url = data.baseUrl+'/users/getUserInfo'
    headers = {"Content-Type": "application/json"}
    try:
        f = open('localStorage.json', 'r')
        global cookie
        cookie = json.loads(f.read())
        f.close()

        if not cookie:
            login()
    except:
        login()

def login():
    Interface.creatLoginWindow()

    #标签 用户名密码
    tk.Label(Interface.login,text='用户名:').place(x=100,y=150)
    tk.Label(Interface.login,text='密码:').place(x=100,y=190)
    #用户名输入框
    global entry_usr_name
    entry_usr_name=tk.Entry(Interface.login)
    entry_usr_name.place(x=160,y=150)
    #密码输入框
    global entry_usr_pwd
    entry_usr_pwd=tk.Entry(Interface.login,show='*')
    entry_usr_pwd.place(x=160,y=190)

    #登录按钮
    bt_login=tk.Button(Interface.login,text='登录',command=checkLogin)
    bt_login.place(x=140,y=230)

    Interface.loginWindowLoop()


def checkLogin():
    url = loginUrl
    headers = {"Content-Type": "application/json"}
    #输入框获取用户名密码
    account=entry_usr_name.get()
    password=entry_usr_pwd.get()
    #获取密码的MD5值
    md=hashlib.md5(password.encode())	# 创建md5对象
    md5pwd=md.hexdigest()	# md5加密

    data = {
        "username": account,
        "password": md5pwd
    }

    cookie = MyRequest.request(url, headers, "post", json=data)
    
    match cookie["state"]:
        case 200:
            tkinter.messagebox.showinfo(title="提示",message="登录成功")
            f = open('localStorage.json','w', encoding='utf-8')
            f.write(json.dumps(cookie["data"], indent=4))
            f.close()
            Interface.login.destroy()
        case _:
            tkinter.messagebox.showerror(title="错误", message=cookie["message"])